package org.gluedom.transport;

import java.util.concurrent.Callable;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.gluedom.data.Immutable;

import com.google.common.collect.ImmutableList;

public class ConnectionCallable implements Callable<ImmutableList<Immutable>> {
	private final Connection con;
	private final ImmutableList<Immutable> data;
	private ImmutableList<Immutable> result;

	public ConnectionCallable(Connection con, ImmutableList<Immutable> data) {
		this.con = con;
		this.data = data;
	}

	public ImmutableList<Immutable> call() throws Exception {
		final Lock lock = new ReentrantLock();
		lock.lock();
		try {
			final Condition ready = lock.newCondition();
			Transports.getTransport(con).send(data, new SendCallback() {
				@Override
				public void doCallback(ImmutableList<Immutable> data) {
					lock.lock();
					try {
						result = data;
						ready.signal();
					} finally {
						lock.unlock();
					}
				}
			});
			ready.await();
		} finally {
			lock.unlock();
		}
		return result;
	}
}
